package com.easyOrder.core.context;

import com.easyOrder.core.cache.IRedisCacheClient;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.ContextLoaderListener;

import javax.servlet.ServletContextEvent;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;

public class WebContextLoaderListener extends ContextLoaderListener {
	
	private Logger logger = Logger.getLogger(WebContextLoaderListener.class);
	
	@Autowired
    IRedisCacheClient redis;
	
	@Override
	public void contextDestroyed(ServletContextEvent event) {
		super.contextDestroyed(event);
		MDC.clear();
		// This manually deregisters JDBC driver, which prevents Tomcat 7 from complaining about memory leaks wrto this class
        Enumeration<Driver> drivers = DriverManager.getDrivers();
        while (drivers.hasMoreElements()) {
            Driver driver = drivers.nextElement();
            try {
                DriverManager.deregisterDriver(driver);
                logger.info(String.format("deregistering jdbc driver: %s", driver));
            } catch (SQLException e) {
            	logger.info(String.format("Error deregistering driver %s", driver), e);
            }

        }
        redis.close();
	}
}
